package com.lemon.boot.common.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.lemon.boot.common.entity.LoginUserDetail;
import com.lemon.boot.common.properties.TenantConfigProperties;
import com.lemon.boot.common.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.schema.Column;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

/**
 * @author 李猛
 * @datetime 2024/2/19 16:57
 * @description 多租户配置
 */
@Slf4j
public class MultiTenantHandler implements TenantLineHandler {
    private final TenantConfigProperties properties;

    public MultiTenantHandler(TenantConfigProperties properties) {
        this.properties = properties;
    }

    @Override
    public Expression getTenantId() {
        String token = JwtUtil.getToken();
        if(StringUtils.hasText(token)){
            Long tenantId = JwtUtil.getCurrentUser(token).getTenantId();
            if(Objects.nonNull(tenantId)){
                return new LongValue(tenantId);
            }
        }
        return new LongValue(0);
    }

    @Override
    public String getTenantIdColumn() {
        return properties.getTenantColumnId();
    }

    @Override
    public boolean ignoreTable(String tableName) {
        return properties.getTenantIgnoreTable().contains(tableName);
    }

    @Override
    public boolean ignoreInsert(List<Column> columns, String tenantIdColumn) {
        return TenantLineHandler.super.ignoreInsert(columns, tenantIdColumn);
    }
}
